package edu.ege.thesis.query.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.rdf.model.RDFNode;

import edu.ege.thesis.exceptionhandling.AppException;
import edu.ege.thesis.model.VoidDO;

public class SPARQLQueryDAO {
  Logger logger = LoggerFactory.getLogger(SPARQLQueryDAO.class);	
  private String endpoint;
  private String queryString;
  QueryExecution qexec;
  
public SPARQLQueryDAO(String endpoint) {
	super();
	this.endpoint = endpoint;
}

public SPARQLQueryDAO(String endpoint, String queryString) {
	super();
	this.endpoint = endpoint;
	this.queryString = queryString;
}

public boolean initialize(){
	 Query query = QueryFactory.create(queryString);
     qexec = QueryExecutionFactory.sparqlService(endpoint, query);
     if (qexec!=null)
       return true;
     else
       return false;
}

public RDFNode getElement(String queriedElement){
	RDFNode element = null;
	try {
		if(qexec==null) throw new AppException("Query Execution could not be constructed...");
        Iterator<QuerySolution> rs = qexec.execSelect() ;
        for ( ; rs.hasNext() ; )
        {
            QuerySolution soln = rs.next() ;
            element = soln.get(queriedElement);
            logger.info(element.toString());
        }
        
      } catch(AppException e){
    	  logger.error(e.getMessage());
      } 
	  return element;
}

public Collection<VoidDO> findProvenanceQueriedVoidDOs(){
	Collection<VoidDO> provenanceRelatedVoidDOs = new ArrayList<VoidDO>();
	try {
		if(qexec==null) throw new AppException("Query Execution could not be constructed...");
        Iterator<QuerySolution> rs = qexec.execSelect() ;
        for ( ; rs.hasNext() ; )
        {
            QuerySolution soln = rs.next() ;
            RDFNode datasetNode = soln.get("?dataset");
			RDFNode provenanceRelatedNode = soln.get("?creator");
            VoidDO voidDO = new VoidDO(datasetNode,provenanceRelatedNode);
            provenanceRelatedVoidDOs.add(voidDO);
        }
        
      } catch(AppException e){
    	  logger.error(e.getMessage());
      } 
	  return provenanceRelatedVoidDOs;
}

public void closeQueryConnection(){
	qexec.close();
}
public String getEndpoint() {
	return endpoint;
}
public void setEndpoint(String endpoint) {
	this.endpoint = endpoint;
}

public String getQueryString() {
	return queryString;
}

public void setQueryString(String queryString) {
	this.queryString = queryString;
}
  

  
}
